﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using PSE.Framework.ErrorLogging;

namespace ConfigurationManager.View.Dialog
{
    public partial class frmInstance : Form
    {
        Model.Instance _instance;
        List<Model.Product> _products;

        public frmInstance(List<Model.Product> products)
        {
            InitializeComponent();
            this.CenterToScreen();

            _products = products;
            cboProduct.ValueMember = "Id";
            cboProduct.DisplayMember = "Name";
            cboProduct.DataSource = _products;

            this.Text = "Inclusão de Instância";
        }

        public frmInstance(List<Model.Product> products, Model.Instance instance)
            : this(products)
        {
            _instance = instance;
            txtCode.Text = _instance.Id.ToString();
            txtName.Text = _instance.Name;
            txtHostName.Text = _instance.HostName;
            txtPort.Text = Convert.ToString(_instance.Port);
            cboProduct.SelectedValue = _instance.Product.Id;
            cboProduct.Enabled = false;//nao permitir alterar o produto por ser chave
            this.Text = "Edição de Instância";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (_instance == null)
                    _instance = new ConfigurationManager.Model.Instance();

                _instance.Name = txtName.Text;
                _instance.HostName = txtHostName.Text;
                _instance.Port = Convert.ToInt32(string.IsNullOrEmpty(txtPort.Text) ? "0" : txtPort.Text);
                _instance.Product.Id = (int)cboProduct.SelectedValue;
                _instance.Product.Name = ((Model.Product)cboProduct.SelectedItem).Name;

                Model.Instance.Save(_instance);
                MessageBox.Show("Instância salva com sucesso!", "Process Manager Configuration", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (ValidationException ex)
            {
                MessageBox.Show(ex.Message, "Atenção");
            }
            catch (Exception ex)
            {
                //EventLog.WriteEntry("Process Manager - Configuration Manager", ex.ToString(), EventLogEntryType.Error);
                Program.HandleException(ex);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
